<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div>
    <button id="btn1">请求</button>
    <button id="btn2">取消</button>
  </div>

  <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>

  <script>
    const oBtn1 = document.getElementById('btn1')
    const oBtn2 = document.getElementById('btn2')

    // 创建一个自定义配置axios对象
    const myaxios = axios.create({
      baseURL: 'http://localhost:3000'
    })
    // 获取请求对象
    const CancelToken = axios.CancelToken
    const source = CancelToken.source();

    oBtn1.onclick = function () {
      myaxios({
        url: '/login',
        method: 'GET',
        params: {
          name: 'aa',
          pass: '123'
        },
        // 给请求添加标记
        cancelToken: source.token,
      }).then(mes => {
        console.log(mes.data);
      }).catch(err => {
        console.log(err);
        // 判断是否被取消
        if (axios.isCancel(err)) {
          console.log("取消了");
        }
      })
    }
    oBtn2.onclick = function () {
      console.log(1);
      //取消请求
      source.cancel("请求取消了 ");
    }
  </script>
</body>

</html>